<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../css/bootstrap.css">
    <!-- 使用needs-validation需要依赖jQuery和bootstrap.js，注意导入的顺序不能反 -->
    <script src="../js/jquery-3.7.1.min.js"></script>
    <script src="../js/bootstrap.bundle.js"></script>
    <title>表单校验</title>
</head>
<body>
    <div class="container">
        <!-- needs-validation使表单校验生效，在表单提交时才进行校验 -->
        <!-- 添加 novalidate 使H5默认的表单校验失效-->
        <form class="needs-validation" novalidate> 
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" class="form-control" id="username" placeholder="用户名" required>
                <!-- 用div装校验通过和不通过的文字 -->
                <div class="valid-feedback">通过</div>
                <div class="invalid-feedback">请填写用户名</div>
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" class="form-control" id="password" placeholder="密码" required>
                <div class="valid-feedback">通过</div>
                <div class="invalid-feedback">请填写密码</div>
            </div>
            <div class="form-group form-check">
                <label class="form-check-label">
                    <input type="checkbox" class="form-check-input" required>我同意协议
                    <div class="valid-feedback">通过</div>
                    <div class="invalid-feedback">请同意协议再提交</div>
                </label>
            </div>
            <button type="submit" class="btn btn-primary">提交</button>
        </form>
    </div>
    
</body>
<script>
   (function() {
  'use strict';
  window.addEventListener('load', function() {
    var forms = document.getElementsByClassName('needs-validation');
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
</script>
</html>